package com.blb.dslock_demo.db;

import java.sql.*;

/**
 * 商品
 */
public class ProductDAO {

    /**
     * 商品减库存
     * 启动事务
     * 查询商品库存 for update
     * if(库存>0){
     *     更新库存-1
     * }
     * 提交事务
     */
    public void reduceStock(Long productId){
        //获得连接
        try(Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sys_product?serverTimezone=GMT", "root", "123456")) {
            //获得statement
            PreparedStatement ps = conn.prepareStatement("select * from sys_product where id = ? for update");
            ps.setLong(1, productId);
            //设置事务手动提交
            conn.setAutoCommit(false);
            //执行查询,上悲观锁
            ResultSet resultSet = ps.executeQuery();
            if (resultSet.next()) {
                int stock = resultSet.getInt("stock");
                //判断库存大于0，就执行扣减库存
                if(stock > 0) {
                    PreparedStatement ps2 = conn.prepareStatement("update sys_product set stock = stock - 1 where id = ?");
                    ps2.setLong(1, productId);
                    ps2.executeUpdate();
                    System.out.println("扣库存成功");
                }else{
                    System.out.println("库存不足");
                }
            }
            //提交事务
            conn.commit();
        }catch (SQLException ex){
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ProductDAO dao = new ProductDAO();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                dao.reduceStock(2L);
            }).start();
        }
    }
}
